//
//  ThirdPartNickNameView.m
//  Growth
//
//  Created by Hobo.Chen on 6/5/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "ThirdPartNickNameView.h"
#import "WebConnetionArray.h"
#import  "WebRequest.h"

#import "RegexKitLite.h"

#import "NotificationEngine.h"

static WebConnectionArray *verifyNicName_connetion;
static WebConnectionArray *createNewUser_Connection;


@implementation ThirdPartNickNameView

-(id)initWithUserInfo:(NSDictionary *)userInfoDict platformId:(int)platformId{
    
   
    _platformId = platformId;
    
    userInfoDictionary = [userInfoDict copy];
    
    [super init];
    return self;
    
}

- (void)dealloc{
    
    if (verifyNicName_connetion != nil) {
        verifyNicName_connetion.connectionDelegate = nil;
        [verifyNicName_connetion release];
        verifyNicName_connetion = nil;
    }
    
    if (createNewUser_Connection != nil) {
        createNewUser_Connection.connectionDelegate = nil;
        [createNewUser_Connection release];
        createNewUser_Connection = nil;
    }
    
    [nickNameTextField release];
    [userInfoDictionary release];
    [super dealloc];
    
}



#pragma mark 完成 Action
- (IBAction)doneAction:(id)sender{
    
    _isDone = YES;
    
    [self verifyNickName];
    
   
    
    
}
 


- (void)verifyNickName{
    
    BOOL isNickName = [nickNameTextField.text isMatchedByRegex:REGEX_NICKNAME];

    if (!isNickName) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"昵称格式错误！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;
        
    }
    
    
    NSMutableURLRequest * request = [WebRequest verifyNickNameRequest:nickNameTextField.text];
    
    CLog(@"request %@", request);
    if (verifyNicName_connetion != nil) {
        verifyNicName_connetion.connectionDelegate = nil;
    }
    verifyNicName_connetion = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];

    
}


#pragma mark -WebConnection delegate

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    CLog(@"info %@",  dict);
    [LoadingView hideWithAnimated:YES];
    
    if (dict==nil) {
        return;
    }
    
    
    //验证昵称
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/verify/nickname?nickname=%@",UCENTERBASEURL,[nickNameTextField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]) {
        
        if ([[dict objectForKey:@"object"] boolValue]) {//该账户不存在,可以创建新账号
            
            if (_isDone) {
                [self  createNewQQUser:nickNameTextField.text];
            }
          
            
            return;
            
        }  
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"该昵称已被注册，换一个吧！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
            
        }
        return;
        
    }
    
    
    //注册
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/user/binding",UCENTERBASEURL]]) {//返回 token userid
        
        NSDictionary *dictionary = [dict objectForKey:@"object"];
        
        //save usre info
        NSInteger errorCode = [[dictionary objectForKey:@"errorCode"] intValue];
        
        if((errorCode == 0 || errorCode == 6) &&[[dictionary allKeys] containsObject:@"userId"]){
            
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userNickname"] forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
            
            
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"Ucenter-Code"] forKey:@"Ucenter-Code"];
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"Ucenter-VerifyCode"] forKey:@"Ucenter-VerifyCode"];
            
            
            //登陆成功
            [[NotificationEngine sharedNotificationEngine] postDeviceToken];
            
            [self loginSuccess];
            
            
        }
        else{
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"服务器连接错误！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            
        }
        
        return;
        
    }
    

        
	    
}

- (void)connectionArrayError:(NSError *)error{
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];    
}


#pragma mark
#pragma mark 登陆成功处理
- (void)loginSuccess{
    
    CLog(@"thirdPart loginSuccess");
    
    [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:REGIST_LOGIN_KEY];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"isFirstInApp"];
    
    switch (_platformId) {
        case 1:
        {
            NSString *uidStr = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] stringValue];
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: uidStr, @"uid", nil];
            [MobClick event:MobClick_Register_Sina attributes:dict];
            break;
        }
        case 2:
        {
            NSString *uidStr = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] stringValue];
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: uidStr, @"uid", nil];
            [MobClick event:MobClick_Register_QQ attributes:dict];
            break;
        }
        default:
            break;
    }

    
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
    
    
}



#pragma mark --
#pragma mark 第三方建新账号zhuce

-(void)createNewQQUser:(NSString *)nickName{ 
    
    if (_platformId == 2) { //qq
        
        NSString *userName = nickName;
        NSString *userPhoto = [userInfoDictionary objectForKey:@"figureurl_1"];
        NSString *gender = [userInfoDictionary objectForKey:@"gender"];
        
        if ([gender isEqualToString:@"男"]) {
            
            gender = @"0";
            
        }
        else{
            
            gender = @"1";
            
        }
        
        
        CLog(@"qq_usrinfoDict %@", userInfoDictionary);
        
        NSString *openId = [[NSUserDefaults standardUserDefaults] valueForKey: QQOpenId];
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"bindingType\":\"%@\",\"appId\":%d,\"token\":\"%@\",\"nickname\":\"%@\",\"platform\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\"}",@"new",1,openId,userName,@"qq",userPhoto,gender];
        
        
        //   NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest userBindingWith:_jsonData];
        CLog(@"request %@", request_derectIn);
        if (createNewUser_Connection != nil) {
            createNewUser_Connection.connectionDelegate = nil;
        }
        createNewUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];
        
    }
    
    
    
    
    if (_platformId == 1) { //weibo
        
        NSString *userName = nickName;
        
        NSString *userPhoto = [userInfoDictionary objectForKey:@"profile_image_url"];
        NSString *gender = [userInfoDictionary objectForKey:@"gender"];
        
        if ([gender isEqualToString:@"f"]) {
            
            gender = @"1";
            
        }
        else{
            
            gender = @"0";
            
        }

        
        
        CLog(@"qq_usrinfoDict %@", userInfoDictionary);
        NSString *token = [userInfoDictionary objectForKey:@"id"];
        
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"bindingType\":\"%@\",\"appId\":%d,\"token\":\"%@\",\"nickname\":\"%@\",\"platform\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\"}",@"new",1,token,userName,@"sina",userPhoto,gender];
        
      
        CLog(@"theBodyString  %@", theBodyString);
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest userBindingWith:_jsonData];
        CLog(@"request %@", request_derectIn);
        if (createNewUser_Connection != nil) {
            createNewUser_Connection.connectionDelegate = nil;
        }
        createNewUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];
        
    }
    
    
    
}





- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    
    
    self.navigationItem.title = @"输入昵称";
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release]; 
    
    
    [super viewDidLoad];
    
    if (_platformId == 1) { //weibo
        
        nickNameTextField.text = [userInfoDictionary objectForKey:@"name"];
    }
    else{ //qq
        
        nickNameTextField.text = [userInfoDictionary objectForKey:@"nickname"];
    }

    [self verifyNickName];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
